<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/19
 * Time: 10:15
 */
namespace app\admin\controller;

use app\admin\model\BusinessMobel;
use app\admin\model\MemberModel;
use app\admin\model\OrderModel;
use app\admin\model\RoleModel;
use app\admin\model\DepartmentModel;
use think\Db;

class Business extends Base
{
    /**
     * 业务管理
     * 黄
     * 18-4-19
    */
    public function index ()
    {

    }
    //客户信息录入
    public function businAdd (){
        $uid = session('id');
        $date = time();
        $business = new BusinessMobel();
        if(request()->isPost()){
            $param = input('post.');
            $param['first_relation'] = $uid;
            $param['entry_time'] = $date;
            $param['create_uid'] = $uid;
            $param['source'] = 0;//客户来源

            $flag = $business->getBusinAdd($param);
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
        //客户等级
        $gradeArr = Db::name('member_attr')->where(['pid'=>1])->select();
        //客户状态
        $statusArr = Db::name('member_attr')->where(['pid'=>5])->select();
		foreach($statusArr as $key=>$val){
			if($val['id'] == 8 || $val['id'] == 9){
				unset($statusArr[$key]);
			}
		}
        $this->assign([
            'gradeArr' => $gradeArr,
            'statusArr' => $statusArr
        ]);
        return $this->fetch();
    }
    //我的跟踪
    public function trackMem ()
    {
        if (request()->isAjax()) {
			$uid = session('id');
            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $where = [];
            if (!empty($param['name'])) {
                $where['name'] = ['like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['phone'])) {
                $where['phone'] = ['like', '%' . $param['phone'] . '%'];
            }
            if (!empty($param['grade'])) {
                $where['grade'] = $param['grade'];
            }
            $where['status'] = 6;//强制使用状态
            $member = new MemberModel();
            $selectResult = $member->getMemberByWhere($where, $offset, $limit);
            foreach($selectResult as $key => $vo){
                $vo['status'] = Db::name('member_attr')->where(['id'=>$vo['status']])->value('name');
                $vo['grade'] = Db::name('member_attr')->where(['id'=>$vo['grade']])->value('name');
				if($vo['share'] == 1){
					$vo['operate'] = showOperate($this->makeButton2($vo['id']));
				}else{
					$vo['operate'] = showOperate($this->makeButton1($vo['id']));
				}

				if ($vo['relation_id'] != $uid) {
                    unset($selectResult[$key]);
                }
            }
            $return['total'] = $member->getAllMember($where);  // 总数据
            $return['rows'] = $selectResult;
            return json($return);
        }
        //客户等级
        $gradeArr = Db::name('member_attr')->where(['pid'=>1])->select();
        $this->assign([
            'gradeArr' => $gradeArr
        ]);
        return $this->fetch();
    }
	/**
	 * 客户分享
	 * 修改分享状态
	 * @ share
	 * 黄
	 */
	 public function shareArtic(){
		 if (request()->isAjax()) {
			 $param = input('post.');
			 $id = $param['m_id'];
			 $member = new MemberModel();
			 $flag = $member->shareStatus($id);
			 return json($flag);
		 }
 	 }
    //我的订单
	 public function myOrder ()
	 {
		 $uid = session('id');
		 if(request()->isAjax()){
			 $param = input('param.');
             $limit = $param['pageSize'];
             $offset = ($param['pageNumber'] - 1) * $limit;
             $where = [];
             //客户姓名
             if(!empty($param['stu_name'])){
                 $where['stu_name'] = array('like','%'.$param['stu_name'].'%');
             }
             //时间
             if(!empty($param['c_time'])){
                 $start_time = strtotime(explode(" - ",$param['c_time'])[0]);
                 $end_time = strtotime(explode(" - ",$param['c_time'])[1]);
                 $where['c_time'] = array('between',[$start_time,$end_time]);
             }
             $where['delete_status'] = array('neq',1);

             $order = new OrderModel();

             //所属咨询师(成交人员)
             if(!empty($param['depart_id']) || !empty($param['staff'])){
                 // 搜人
                 $staff = input('param.staff');
                 $ids = DB::name('user')->where('real_name','like', '%'.$staff.'%')->column('id');
                 $idArr =[];
                 if(!empty(session('can_see')[0])){
                     foreach (session('can_see') as $v){
                         foreach($ids as $va){
                             if($v['create_uid'] == $va){
                                 array_push($idArr,$v['create_uid']);
                             }
                         }
                     }
                 }
                 if($staff && empty($idArr)){
                     $idArr =[-1];
                 }
                 // 搜部门
                 $departId = input('param.depart_id');
                 $departModel = new DepartmentModel();
                 $roleModel = new RoleModel();
                 $departIds = $departModel->getSonsByPid($departId);
                 array_push($departIds,['id'=>$departId]);
                 $roles = [];
                 foreach ($departIds as $k => $v){
                     if(DB::name('role')->where('department_id',$v['id'])->find()) {
                         $roles[$k] = $roleModel->getUsersByDepartId($v['id']);
                     }
                 }
                 $users = [];
                 foreach ($roles as $k => $v){
                     foreach($v as $ke => $va){
                         array_push($users,$va);
                     }
                 }
                 $users = array_merge(array_filter($users));
                 $usersArr = [];
                 if(!empty(session('can_see')[0])){
                     foreach (session('can_see') as $v){
                         foreach($users as $va){
                             if($v['create_uid'] == $va){
                                 array_push($usersArr,$v['create_uid']);
                             }
                         }
                     }
                 }
                 if($departId && empty($usersArr)){
                     $usersArr =[-1];
                 }

                 $order->where(function($query)use($idArr){
                     foreach($idArr as $v){
                         $query->whereOr('consultant',$v);
                     }
                 });
                 $order->where(function($query)use($usersArr){
                     foreach($usersArr as $v){
                         $query->whereOr('consultant',$v);
                     }
                 });

             }else{
                 $where['consultant'] = $uid;
             }

			 $orderArr = $order->getMyOrder($where, $offset, $limit);
             foreach ($orderArr as $key=>&$value){
                 $u_id = $value['m_id'];
                 $grade = $value['grade'];//层次
                 $payment_method  = $value['payment_method'];//缴费方式
                 $consultant = $value['consultant'];
                 $mem_phone = Db::name('member')->where(['id'=>$u_id])->value('phone');//查询当前订单的客户信息
                 $gradeN = Db::name('product_attr')->where(['id'=>$grade])->value('name');//获取当前层次
                 $payment_methodN = Db::name('product_attr')->where(['id'=>$payment_method])->value('name');
                 $consultantN = Db::name('user')->where('id',$consultant)->value('real_name');
                 $value['phone'] = $mem_phone;
                 $value['gradeN'] = $gradeN;
                 $value['payment_methodN'] = $payment_methodN;
                 $value['consultantN'] = $consultantN;
                 $value['operate'] = showOperate($this->makeButton3($value['id']));
                 $value['c_time'] = date('Y-m-d',$value['c_time']);
             }

			 $member = new MemberModel();
 			 $member->where(function($query)use($idArr){
 				foreach($idArr as $v){
 					$query->whereOr('create_uid',$v);
 				}
 			 });
 			 $member->where(function($query)use($users){
 				foreach($users as $v){
 					$query->whereOr('create_uid',$v);
 				}
 			 });
             $return['total'] = $order->getAllOrder($where);  // 总数据
             $return['rows'] = $orderArr;
             $return['sum'] = 0;
             foreach($return['rows'] as $val){
                 //增加总金额
                 $return['sum'] += $val['total_amount'];
             }
             return json($return);
		 }
		 return $this->fetch();
	 }
    /**
     * 订单详细信息
     * $id 订单id
     */
    public function orderInfo ()
    {
        $id = input('id');
        $order = new OrderModel();
        $ordeInfo = $order->getOrderInfo($id);
        //层次
        $gradeN = Db::name('product_attr')->where('id',$ordeInfo['grade'])->value('name');
        //制度
        $systemN = Db::name('product_attr')->where('id',$ordeInfo['system'])->value('name');
        //教育模式
        $acquisition_modeN = Db::name('product_attr')->where('id',$ordeInfo['acquisition_mode'])->value('name');
        //缴费方式
        $payment_methodN = Db::name('product_attr')->where('id',$ordeInfo['payment_method'])->value('name');
        //支付方式
		$ordeInfo['pay_typeN'] = Db::name('member_attr')->where(['id'=>$ordeInfo['pay_type']])->value('name');
        //订单状态
        switch ($ordeInfo['status']){
            case 1:
                $ordeInfo['statusN'] = '进行中';
                break;
            case 2:
                $ordeInfo['statusN'] = '已完成';
                break;
            case 3:
                $ordeInfo['statusN'] = '退款';
                break;
            default:
                $ordeInfo['statusN'] = '其他';
        }
        //创建时间
        $ordeInfo['c_time'] = date('Y-m-d',$ordeInfo['c_time']);
        //所属咨询师
        $ordeInfo['consultantN'] = Db::name('user')->where('id',$ordeInfo['consultant'])->value('real_name');
        //创建人
        $ordeInfo['createN'] = Db::name('user')->where('id',$ordeInfo['create_uid'])->value('real_name');

        $ordeInfo['gradeN'] = $gradeN;
        $ordeInfo['systemN'] = $systemN;
        $ordeInfo['acquisition_modeN'] = $acquisition_modeN;
        $ordeInfo['payment_methodN'] = $payment_methodN;
        $this->assign([
            'ordeInfo' => $ordeInfo
        ]);
        return $this->fetch();
    }

    /**
     * 新增资源客户
     * 由主管和主任分配的资源客户
     * @status @first_relation @source
     */
    public function resouMember(){
        if (request()->isAjax()) {
            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $where = [];
            if (!empty($param['name'])) {
                $where['name'] = ['like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['phone'])) {
                $where['phone'] = ['like', '%' . $param['phone'] . '%'];
            }
            //时间
            if(!empty($param['time'])){
                $start_time = strtotime(explode(" - ",$param['time'])[0].'00:00:00');
                $end_time = strtotime(explode(" - ",$param['time'])[1].'24:59:59');
                $where['entry_time'] = array('between',[$start_time,$end_time]);
            }
            $where['delete_status'] = array('neq',2);
            $where['first_relation'] = session('id');//第一录入人
            $where['status'] = 9;   //状态(由分配来的客户状态只能为资源库客户)
            $where['grade'] = 0;    //等级(由分配来的客户等级无状态)
            $where['source'] = 1;    //来源(由分配来的客户来源都是客户资源客户)
            $where['create_uid'] = session('id'); //创建人
            $member = new MemberModel();

            $selectResult = $member->getMemberByWhere($where, $offset, $limit);
            foreach($selectResult as $key=>&$vo){
                $vo['statusN'] = Db::name('member_attr')->where(['id'=>$vo['status']])->value('name');
                $vo['operate'] = showOperate($this->makeButton4($vo['id']));
            }
            $return['total'] = $member->getAllMember($where);  // 总数据
            $return['rows'] = $selectResult;
            return json($return);
        }
        //客户等级
        $gradeArr = Db::name('member_attr')->where(['pid'=>1])->select();
        //客户状态
        $statusArr = Db::name('member_attr')->where(['pid'=>5])->select();
        $this->assign([
            'gradeArr' => $gradeArr,
            'statusArr' => $statusArr
        ]);
        return $this->fetch();
    }
    /**
     * 拼装操作按钮
     * @param $id 跟踪记录
     * @return array
     */
    private function makeButton1($id)
    {
        return [
            '跟踪记录' => [
                'auth' => 'business/trackmem',
                'href' => url('member/memberedit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste',
            ],
	        '资源分享' => [
	            'auth' => 'business/shareartic',
	            'href' => 'javascript:shareartic('.$id.')',
	            'btnStyle' => 'primary',
	            'icon' => 'fa fa-paste',
			]
        ];
    }
	private function makeButton4($id)
    {
        return [
            '跟踪记录' => [
                'auth' => 'business/trackmem',
                'href' => url('member/memberedit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste',
            ]
        ];
    }
    /**
     * 查看信息 $id
     */
    private function makeButton2($id)
    {
        return [
			'跟踪记录' => [
                'auth' => 'business/trackmem',
                'href' => url('member/memberedit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste',
            ],
            '已分享' => [
                'auth' => 'business/shareartic',
                'href' => 'javascript:void(0)',
                'btnStyle' => 'danger',
                'icon' => 'fa fa-search',
            ]
        ];
    }
    /**
     *添加按钮 $id
     */
    private function makeButton3($id)
    {
        return [
            '查看订单' => [
                'auth' => 'business/orderinfo',
                'href' => url('business/orderinfo', ['id' => $id]),
                'btnStyle' => 'success',
                'icon' => 'fa fa-paste',
            ]
        ];
    }
}
